package ymlgo

import (
	"devOpsApi/config"
	"github.com/kataras/iris"
	"gopkg.in/yaml.v2"
	"io/ioutil"
	"os"
)

type ConfigEmail struct {
	ServerHost string `yaml:"ServerHost"`
	ServerPort string `yaml:"ServerPort"`
	FromEmail  string `yaml:"FromEmail"`
	FromPasswd string `yaml:"FromPasswd"`
	IsOpen     bool   `yaml:"IsOpen"`
}

func NewConfigEmail() *ConfigEmail {
	data, _ := ioutil.ReadFile(config.ConfigEmailPath)
	t := ConfigEmail{}
	yaml.Unmarshal(data, &t)
	return &t
}

func (c *ConfigEmail) Update(ctx iris.Context) error {
	c.ServerHost = ctx.PostValue("ServerHost")
	c.ServerPort = ctx.PostValue("ServerPort")
	c.FromEmail = ctx.PostValue("FromEmail")
	c.FromPasswd = ctx.PostValue("FromPasswd")
	IsOpen, err := ctx.PostValueBool("IsOpen")
	if err != nil {
		return err
	}
	c.IsOpen = IsOpen
	out, err := yaml.Marshal(c)
	if err != nil {
		return err
	}
	if err := ioutil.WriteFile(config.ConfigEmailPath, out, os.ModePerm); err != nil {
		return err
	}
	return nil
}
